import axios from 'axios'
import config from './config'

// 创建axios实例
const api = axios.create({
  baseURL: config.getBaseURL(),
  timeout: 5000
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    console.log('发送请求:', config.method.toUpperCase(), config.url)
    console.log('请求数据:', config.data)
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    console.log('收到响应:', response.status, response.data)
    return response
  },
  error => {
    console.error('响应错误:', error.response || error)
    return Promise.reject(error)
  }
)

// 员工信息相关API
export const employeeAPI = {
  getAll: (page, pageSize) => api.get('/api/employees', { params: { page, per_page: pageSize } }),
  getById: (id) => api.get(`/api/employees/${id}`),
  create: (data) => api.post('/api/employees', data),
  update: (id, data) => api.put(`/api/employees/${id}`, data),
  delete: (id) => api.delete(`/api/employees/${id}`),
  exportResume: (employeeId, templateId) => api.get(`/api/employees/${employeeId}/export/${templateId}`, {
    responseType: 'blob'
  }),
  exportExcel: () => api.get('/api/employees/export/excel', { responseType: 'blob' }),
  // 简历附件相关操作
  getAttachments: (employeeId) => {
    return api.get(`/api/employees/${employeeId}/attachments`)
  },
  addAttachment: (employeeId, file, description) => {
    const formData = new FormData()
    formData.append('file', file)
    if (description) {
      formData.append('description', description)
    }
    return api.post(`/api/employees/${employeeId}/attachments`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  deleteAttachment: (employeeId, attachmentId) => {
    return api.delete(`/api/employees/${employeeId}/attachments/${attachmentId}`)
  },
  // 下载附件
  download: (attachmentId) => {
    return api.get(`/api/attachments/download/${attachmentId}`, {
      responseType: 'blob'
    })
  },
  // 获取附件预览URL
  getPreviewUrl: (attachmentId) => {
    // 返回预览URL，与 attachmentAPI 保持一致
    return `${config.getBaseURL()}/api/attachments/download/${attachmentId}`
  }
}

// 证书相关API
export const certificateAPI = {
  getAll: (page, pageSize, params) => api.get('/api/certificates', { 
    params: { 
      page, 
      per_page: pageSize,
      ...params 
    } 
  }),
  
  getById: (id) => {
    return api.get(`/api/certificates/${id}`);
  },
  
  create: (data) => api.post('/api/certificates', data),
  
  update: (id, data) => api.put(`/api/certificates/${id}`, data),
  
  delete: (id) => api.delete(`/api/certificates/${id}`),
  
  // 附件相关操作
  getAttachments: (certificateId) => {
    return api.get(`/api/certificates/${certificateId}/attachments`);
  },
  
  addAttachment: (certificateId, file, description = '', uploader = '系统') => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('description', description);
    formData.append('uploader', uploader);
    return api.post(`/api/certificates/${certificateId}/attachments`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  },
  
  deleteAttachment: (certificateId, attachmentId) => {
    return api.delete(`/api/certificates/${certificateId}/attachments/${attachmentId}`);
  },
  
  // 下载附件
  download: (attachmentId) => {
    return api.get(`/api/attachments/download/${attachmentId}`, {
      responseType: 'blob'
    });
  },
  
  // 获取附件预览URL
  getPreviewUrl: (attachmentId) => {
    return `${config.getBaseURL()}/api/attachments/download/${attachmentId}`;
  },

  getEmployeeCertificates: (employeeId) => api.get(`/api/employees/${employeeId}/certificates`),
  createEmployeeCertificate: (employeeId, data) => api.post(`/api/employees/${employeeId}/certificates`, data),
  updateEmployeeCertificate: (employeeId, id, data) => api.put(`/api/employees/${employeeId}/certificates/${id}`, data),
  deleteEmployeeCertificate: (employeeId, id) => api.delete(`/api/employees/${employeeId}/certificates/${id}`),
  exportExcel: () => api.get('/api/certificates/export/excel', { responseType: 'blob' })
}

// 证书名称管理API
export const certificateNameAPI = {
  getAll: (page, pageSize, params) => api.get('/api/certificate-names', {
    params: {
      page,
      per_page: pageSize,
      ...params
    }
  }),
  getById: (id) => api.get(`/api/certificate-names/${id}`),
  create: (data) => api.post('/api/certificate-names', data),
  update: (id, data) => api.put(`/api/certificate-names/${id}`, data),
  delete: (id) => api.delete(`/api/certificate-names/${id}`),
  exportExcel: () => api.get('/api/certificate-names/export/excel', { responseType: 'blob' })
}

// 项目经验相关API
export const projectAPI = {
  getAll: (employeeId, params = {}) => api.get(`/api/employees/${employeeId}/projects`, { params }),
  create: (employeeId, data) => api.post(`/api/employees/${employeeId}/projects`, data),
  update: (employeeId, id, data) => api.put(`/api/employees/${employeeId}/projects/${id}`, data),
  delete: (employeeId, id) => api.delete(`/api/employees/${employeeId}/projects/${id}`)
}

// 工作经历相关API
export const workExperienceAPI = {
  getAll: (employeeId, params = {}) => api.get(`/api/employees/${employeeId}/work_experiences`, { params }),
  create: (employeeId, data) => api.post(`/api/employees/${employeeId}/work_experiences`, data),
  update: (employeeId, id, data) => api.put(`/api/employees/${employeeId}/work_experiences/${id}`, data),
  delete: (employeeId, id) => api.delete(`/api/employees/${employeeId}/work_experiences/${id}`)
}

// 简历模板相关API
export const templateAPI = {
  getAll: () => api.get('/api/templates'),
  create: (data) => api.post('/api/templates', data),
  update: (id, data) => api.put(`/api/templates/${id}`, data),
  delete: (id) => api.delete(`/api/templates/${id}`),
  setDefault: (id) => api.put(`/api/templates/${id}/set-default`)
}

// 附件相关API
export const attachmentAPI = {
  // 通用上传附件
  upload: (file, module) => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('module', module);
    
    return api.post('/api/attachments/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  },
  
  // 获取附件信息
  getById: (id) => {
    return api.get(`/api/attachments/${id}`);
  },
  
  // 删除附件
  delete: (id) => {
    return api.delete(`/api/attachments/${id}`);
  },
  
  // 下载附件
  download: (id) => {
    return api.get(`/api/attachments/download/${id}`, { responseType: 'blob' });
  },
  
  // 获取附件预览URL
  getPreviewUrl: (id) => {
    // 返回预览URL
    return `${config.getBaseURL()}/api/attachments/download/${id}`;
  }
};

// 合同管理相关API
export const contractAPI = {
  getAll: (page, pageSize, params) => api.get('/api/contracts', { 
    params: { 
      page, 
      per_page: pageSize,
      ...params 
    } 
  }),
  
  getById: (id) => {
    return api.get(`/api/contracts/${id}`);
  },
  
  create: (data) => api.post('/api/contracts', data),
  
  update: (id, data) => api.put(`/api/contracts/${id}`, data),
  
  delete: (id) => api.delete(`/api/contracts/${id}`),
  
  searchEmployees: (query) => api.get('/api/employees/search', { params: { query } }),
  
  // 附件相关操作
  getAttachments: (contractId) => {
    return api.get(`/api/contracts/${contractId}/attachments`);
  },
  
  addAttachment: (contractId, file, description = '') => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('description', description);
    // 不能手动设置Content-Type，否则会导致415，需让axios自动生成
    return api.post(`/api/contracts/${contractId}/attachments`, formData);
  },
  
  deleteAttachment: (contractId, attachmentId) => {
    return api.delete(`/api/contracts/${contractId}/attachments/${attachmentId}`);
  },
  // 新增导出Excel接口
  exportExcel: () => api.get('/api/contracts/export/excel', { responseType: 'blob' })
}

// 合同信息API（仅用于简历管理弹窗）
export const contractInfoAPI = {
  getByEmployeeId: (employeeId) => api.get(`/api/employees/${employeeId}/contracts`)
}

// 教育背景相关API
export const educationAPI = {
  getAll: (employeeId, params = {}) => api.get(`/api/employees/${employeeId}/educations`, { params }),
  create: (employeeId, data) => api.post(`/api/employees/${employeeId}/educations`, data),
  update: (employeeId, id, data) => api.put(`/api/employees/${employeeId}/educations/${id}`, data),
  delete: (employeeId, id) => api.delete(`/api/employees/${employeeId}/educations/${id}`)
}

export const rewardPunishmentAPI = {
  getEmployeeRewardPunishments: (employeeId) => api.get(`/api/employees/${employeeId}/reward_punishments`),
  createEmployeeRewardPunishment: (employeeId, data) => api.post(`/api/employees/${employeeId}/reward_punishments`, data),
  updateEmployeeRewardPunishment: (employeeId, id, data) => api.put(`/api/employees/${employeeId}/reward_punishments/${id}`, data),
  deleteEmployeeRewardPunishment: (employeeId, id) => api.delete(`/api/employees/${employeeId}/reward_punishments/${id}`),
  exportExcel: () => api.get('/api/reward-punishments/export/excel', { responseType: 'blob' })
}

export default api; 